from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework.generics import CreateAPIView

# Create your views here.
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer


class QQLoginURLView(APIView):
    # 构建跳转链接
    # 生成QQ对象
    def get(self, request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        # 调用生成url的方法
        login_url = qq.get_qq_url()
        # 返回url
        return Response({'login_url': login_url})


class OauthView(CreateAPIView):

    # 指定序列化器
    serializer_class = OauthSerializer
    def get(self, request):
        code = request.query_params.get('code')
        if code is None:
            return Response({'errors': '缺少code值'}, status=400)

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = qq.get_access_token(code)
        openid = qq.get_open_id(access_token)
        # 判断openid和美多是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未绑定
            tjs = TJS(settings.SECRET_KEY, 300)
            data = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': data})
        else:
            # 获取用户对象
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            user.token = token
            response = Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request,response,user)
            return response
            # def post(self, request):

